import axios from "./axios";
import {
	clearEmptyParam
} from './clearEmptyParam'
import Vue from "vue";
import shop from "./shop";

const request = axios.create({
	baseURL: 'https://admin.shop996.top/shop_demo',
	// baseURL: 'https://shop-admin.xzaiyp.top/shop_demo',
	timeout: '5000s',
})

request.interceptors.request.use(config => {

	config.headers['Content-Type'] = "application/x-www-form-urlencoded"

	if (localStorage.getItem('token')) {
		config.headers['X-Access-Token'] = `${localStorage.getItem('token')}`
	}

	if (uni.getStorageSync('language')) {
		config.headers['Language'] = `${uni.getStorageSync('language')}`
	}

	clearEmptyParam(config)

	return config;
})

request.interceptors.response.use(res => {
		if (res.headers['token']) {
			localStorage.setItem('token', res.headers['token'])
		}

		if (res.data.code != 200) {
			uni.$u.toast(res.data.message)
		}

		if (res.data.code == 401) {
			localStorage.removeItem('token')
			uni.navigateTo({
				url: "/pages/login/login"
			})
		}
		return res.data;
	},
	err => {
		console.log(err);
		if (err.response.status == 401) {
			localStorage.removeItem('token')
			// router.replace('/login').catch(()=>{})
			uni.navigateTo({
				url: "/pages/login/login"
			})
		}
		return Promise.reject(new Error(err))
	})

export function handleRequest(key, data, params) {
	if (!shop[key]) {
		return console.error('无效key');
	}

	if (shop[key].auth) {
		if (!localStorage.getItem('token')) {
			uni.navigateTo({
				url: "/pages/login/login"
			})
			console.error('需要登录')
			return {
				then() {}
			};
		}
	}

	return request({
		...shop[key],
		data,
		params
	})
};

export default handleRequest